package com.android.jingweiapp.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.android.jingweiapp.R;
import com.android.jingweiapp.XMLPhase.GetHotWordXMLPhase;
import com.android.jingweiapp.XMLPhase.GetNewsByKeywordXMLPhase;
import com.android.jingweiapp.adapter.CommonAdapter;
import com.android.jingweiapp.adapter.HotWordAdapter;
import com.android.jingweiapp.bean.HotWord;
import com.android.jingweiapp.bean.NewsBean;
import com.android.jingweiapp.util.Contacts;
import com.android.jingweiapp.util.HttpUtil;
import com.android.jingweiapp.widget.MyToast;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 搜索页/搜索结果页
 */
public class SearchActivity extends AppCompatActivity {

    @Bind(R.id.btn_back)
    Button btnBack;
    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.btn_search)
    TextView btnSearch;
    @Bind(R.id.clear_btn)
    TextView clearBtn;
    @Bind(R.id.keyWordView)
    RecyclerView keyWordView;
    @Bind(R.id.resultView)
    ListView resultView;
    @Bind(R.id.keyword_tip)
    TextView keywordTip;

    private ArrayList<NewsBean> newsBeans;
    private CommonAdapter adapter;
    private HotWord hotWord;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_serach);
        ButterKnife.bind(this);
        init();

    }

    private void init() {
        String keyWord = getIntent().getStringExtra(Contacts.KEY.KEY_KEYWORD);
        final int type = getIntent().getIntExtra(Contacts.KEY.KEY_TYPE, -1);
        //  etSearch.requestFocus();
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (newsBeans != null) {
                    newsBeans.clear();//在新的搜索之前移除之前的列表
                }
                if (!TextUtils.isEmpty(etSearch.getText().toString())) {

                    new SearchAsyncTask().execute(etSearch.getText().toString(), String.valueOf(type));
                } else {
                    MyToast.getInstance().show("请输入关键字");
                }
            }
        });

        etSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    clearBtn.setVisibility(View.VISIBLE);//输入框获取焦点之后,清除按钮可见
                }
            }
        });
        clearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearch.setText("");
            }
        });

        hotWord = new HotWord();
        newsBeans = new ArrayList<>();
        adapter = new CommonAdapter(newsBeans, this);
        resultView.setAdapter(adapter);
        resultView.setOnItemClickListener(new MyItemClickListener());


        if (!TextUtils.isEmpty(keyWord)) {
            btnSearch.setText(keyWord);
            resultView.setVisibility(View.VISIBLE);
            keyWordView.setVisibility(View.GONE);
            keywordTip.setVisibility(View.GONE);
            new SearchAsyncTask().execute(keyWord, String.valueOf(type));
        } else {
            resultView.setVisibility(View.GONE);
            keyWordView.setVisibility(View.VISIBLE);
            keywordTip.setVisibility(View.VISIBLE);
            new HotWordAsyncTask().execute();
        }


    }

    /**
     * 获取热词
     */
    public void getHotWord(String result) {
        if (TextUtils.isEmpty(result)) {
            MyToast.getInstance().show("出错了，请重试");

        }
        if (result.equals("nodata")) {
            MyToast.getInstance().show("无更多数据");

            return;
        }
        Gson gson = new Gson();
        hotWord = gson.fromJson(result, HotWord.class);
        HotWordAdapter hotWordAdapter = new HotWordAdapter(SearchActivity.this, hotWord.getData());
        keyWordView.setLayoutManager(new GridLayoutManager(this, 3));
        keyWordView.setAdapter(hotWordAdapter);
        hotWordAdapter.setOnItemClickListener(new HotWordAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, Parcelable data) {
                new SearchAsyncTask().execute(((HotWord.DataEntity) view.getTag()).getContent(), "-1");
            }
        });
    }


    class HotWordAsyncTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }


        @Override
        protected String doInBackground(String[] params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    GetHotWordXMLPhase.createParam(SearchActivity.this),
                    new GetHotWordXMLPhase());
        }

        @Override
        protected void onPostExecute(String str) {
            super.onPostExecute(str);
            getHotWord(str);
        }
    }


    class SearchAsyncTask extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... params) {
            return HttpUtil.postWithContent(Contacts.BASE_URL,
                    GetNewsByKeywordXMLPhase.createParam(SearchActivity.this, params[0], params[1]),
                    new GetNewsByKeywordXMLPhase());
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            dealSearchData(s);
        }
    }

    /**
     * 处理返回的数据
     *
     * @param result：返回的数据
     */
    private void dealSearchData(String result) {
        if (TextUtils.isEmpty(result)) {
            MyToast.getInstance().show("出错了，请重试");
        }
        if (result.equals("nodata")) {
            MyToast.getInstance().show("无搜索结果");
            return;
        }
        resultView.setVisibility(View.VISIBLE);
        keyWordView.setVisibility(View.GONE);
        keywordTip.setVisibility(View.GONE);

        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONArray array = jsonObject.getJSONArray("data");
            for (int i = 0; i < array.length(); i++) {
                newsBeans.add(new NewsBean(array.getJSONObject(i)));
            }
            adapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private class MyItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            NewsBean newsBean = newsBeans.get(position);//获得新闻对象
            int type = newsBean.getType();//获得type

            switch (type) {

                /**
                 * 图片新闻
                 */
                case Contacts.SEARCH_TYPE.PIC_NEWS:
                    startActivity(new Intent(SearchActivity.this, NewsDetailPicActivity.class)
                            .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                            .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TEXT_NEWS));
                    break;
                /**
                 * 视频新闻
                 */
                case Contacts.SEARCH_TYPE.VIDEO_NEWS:
                    startActivity(new Intent(SearchActivity.this, NewsDetailVideoActivity.class)
                            .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                            .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TEXT_NEWS));
                    break;

                case Contacts.SEARCH_TYPE.INFORMATION:
                case Contacts.SEARCH_TYPE.RESPONCE_CONCERN:
                    /**
                     * 经信资讯
                     * 回应关切
                     */
                    startActivity(new Intent(SearchActivity.this, DetailTextActivity.class)
                            .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                            .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TEXT_NEWS));
                    break;
                case Contacts.SEARCH_TYPE.PUBLIC_NOTIFY:
                    //通知
                    startActivity(new Intent(SearchActivity.this, DetailTextActivity.class)
                            .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                            .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.NOTIFY_NEWS));
                    break;
                case Contacts.SEARCH_TYPE.PUBLIC_ANNOUNCE:
                    //通告
                    startActivity(new Intent(SearchActivity.this, DetailTextActivity.class)
                            .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                            .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.ANNOUNCE_NEWS));
                    break;
                case Contacts.SEARCH_TYPE.PUBLIC_ANNALS:
                    //公开年报
                    startActivity(new Intent(SearchActivity.this, DetailTextActivity.class)
                            .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                            .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.REPORT_CONTENT));
                    break;
                case Contacts.SEARCH_TYPE.PUBLIC__REGULATION:
                    //公开制度
                    startActivity(new Intent(SearchActivity.this, DetailTextActivity.class)
                            .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                            .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.REGULATION_CONTENT));
                    break;
                case Contacts.SEARCH_TYPE.SPECIAL_CHANNEL:
                    //经信专栏
                    startActivity(new Intent(SearchActivity.this, NewsDetailPicActivity.class)
                            .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                            .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.SPECIAL_NEWS_SPECIAL));
                    break;
                case Contacts.SEARCH_TYPE.Topic_Point:
                    //专题聚焦
                    startActivity(new Intent(SearchActivity.this, NewsDetailPicActivity.class)
                            .putExtra(Contacts.KEY.KEY_OBJECT, newsBeans.get(position))
                            .putExtra(Contacts.KEY.KEY_TYPE, Contacts.TYPE.TOPIC_NEWS_SPECIAL));
                    break;

            }

        }
    }
}
